package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.Permission;
import cn.tedu.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.获得用户信息
        User user=userMapper.findUserByUsername(username);
        // 2.验证用户存在
        if(user==null){
            return  null;
        }
        // 3.获得用户权限
        List<Permission> permissions=userMapper
                .findUserPermissionsById(user.getId());
        // 4.获得权限的字符串数组
        String[] auth=new String[permissions.size()];
        int i=0;
        for(Permission p: permissions){
            auth[i]=p.getName();
            i++;
        }
        // 5.创建UserDetails对象
        UserDetails details= org.springframework.security.core
                .userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();
        // 6.返回
        return details;
    }
}
